package com.feihe.controller;

import com.feihe.dto.*;
import com.feihe.service.ReservationService;
import com.feihe.service.EncryptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/feihe")
public class ReservationController {
    
    @Autowired
    private ReservationService reservationService;
    
    @Autowired
    private EncryptionService encryptionService;
    
    /**
     * 获取未来7天信息 - 对应 get_day.php
     */
    @PostMapping("/get_day")
    public ApiResponse<List<DayInfo>> getDays(@RequestBody Map<String, Object> requestBody) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 提取memberId（可选验证）
            String memberId = (String) encryptionService.extractField(decryptedData, "memberId");
            
            List<DayInfo> days = reservationService.getDays();
            return ApiResponse.success(days);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取场地信息 - 对应 get_ground.php
     */
    @PostMapping("/get_ground")
    public ApiResponse<List<GroundInfo>> getGrounds(@RequestBody Map<String, Object> requestBody) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 提取memberId（可选验证）
            String memberId = (String) encryptionService.extractField(decryptedData, "memberId");
            
            List<GroundInfo> grounds = reservationService.getGrounds();
            return ApiResponse.success(grounds);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取时间段信息 - 对应 get_time.php
     */
    @PostMapping("/get_time")
    public ApiResponse<List<TimeSlot>> getTimeSlots(@RequestBody Map<String, Object> request) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(request);
            
            // 提取参数
            String day = (String) encryptionService.extractField(decryptedData, "day");
            Object groundObj = encryptionService.extractField(decryptedData, "ground");
            Integer ground = groundObj instanceof Integer ? (Integer) groundObj : 
                           groundObj instanceof String ? Integer.parseInt((String) groundObj) : null;
            
            if (day == null || day.isEmpty() || ground == null) {
                return ApiResponse.error("参数不能为空");
            }
            
            List<TimeSlot> timeSlots = reservationService.getTimeSlots(day, ground);
            return ApiResponse.success(timeSlots);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 创建预约 - 对应 reservation.php
     */
    @PostMapping("/reservation")
    public ApiResponse<Map<String, Object>> createReservation(@RequestBody Map<String, Object> requestBody, 
                                                              HttpServletRequest httpRequest) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(requestBody);
            
            // 将解密后的数据转换为ReservationRequest对象
            ReservationRequest request = encryptionService.parseDecryptedData(decryptedData, ReservationRequest.class);
            
            if (request.getMemberId() == null || request.getMemberId().isEmpty()) {
                return ApiResponse.error("会员ID不能为空");
            }

            if (request.getReservationDate() == null || request.getReservationDate().isEmpty()) {
                return ApiResponse.error("请选择到访日期");
            }

            if (request.getReservationTime() == null || request.getReservationTime().isEmpty()) {
                return ApiResponse.error("请选择到访时间");
            }

            if(request.getRealname() == null || request.getRealname().isEmpty()){
                return ApiResponse.error("请填写访客姓名");
            }

            if(request.getTelephone() == null || request.getTelephone().isEmpty()){
                return ApiResponse.error("请填写访客手机号");
            }

            if (!request.getTelephone().matches("\\d{11}")) {
                return ApiResponse.error("手机号必须为11位数字");
            }

            if (request.getVisitorNumber() == null) {
                return ApiResponse.error("请填写访客人数");
            }

            if (request.getVisitorNumber() <= 0) {
                return ApiResponse.error("访客人数必须为大于0");
            }

            if(request.getType() == null || request.getType().isEmpty()){
                return ApiResponse.error("请选择访客类型");
            }



            Map<String, Object> result = reservationService.createReservation(request, httpRequest);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 取消预约 - 对应 reservation_cancel.php
     */
    @PostMapping("/reservation_cancel")
    public ApiResponse<Void> cancelReservation(@RequestBody Map<String, Object> request) {
        try {
            Object idObj = request.get("id");
            if (idObj == null) {
                return ApiResponse.error("预约ID不能为空");
            }
            
            Long id;
            if (idObj instanceof Integer) {
                id = ((Integer) idObj).longValue();
            } else if (idObj instanceof Long) {
                id = (Long) idObj;
            } else if (idObj instanceof String) {
                id = Long.parseLong((String) idObj);
            } else {
                return ApiResponse.error("预约ID格式错误");
            }
            
            reservationService.cancelReservation(id);
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 签到 - 对应 reservation_check.php
     */
    @PostMapping("/reservation_check")
    public ApiResponse<Void> checkIn(@RequestBody Map<String, Object> request) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(request);
            
            // 提取uniqid参数
            String uniqid = (String) encryptionService.extractField(decryptedData, "uniqid");
            if (uniqid == null || uniqid.isEmpty()) {
                return ApiResponse.error("唯一ID不能为空");
            }
            
            reservationService.checkIn(uniqid);
            return ApiResponse.success();
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取预约详情 - 对应 reservation_detail.php
     */
    @PostMapping("/reservation_detail")
    public ApiResponse<Map<String, Object>> getReservationDetail(@RequestBody Map<String, Object> request) {
        try {
            Object idObj = request.get("id");
            if (idObj == null) {
                return ApiResponse.error("预约ID不能为空");
            }
            
            Long id;
            if (idObj instanceof Integer) {
                id = ((Integer) idObj).longValue();
            } else if (idObj instanceof Long) {
                id = (Long) idObj;
            } else if (idObj instanceof String) {
                id = Long.parseLong((String) idObj);
            } else {
                return ApiResponse.error("预约ID格式错误");
            }
            
            Map<String, Object> detail = reservationService.getReservationDetail(id);
            return ApiResponse.success(detail);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取预约列表 - 对应 reservation_list.php
     */
    @PostMapping("/reservation_list")
    public ApiResponse<List<Map<String, Object>>> getReservationList(@RequestBody Map<String, Object> request) {
        try {
            String memberId = (String) request.get("memberId");
            Integer type = (Integer) request.get("type");
            
            if (memberId == null || memberId.isEmpty() || type == null) {
                return ApiResponse.error("参数不能为空");
            }
            
            List<Map<String, Object>> list = reservationService.getReservationList(memberId, type);
            return ApiResponse.success(list);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * AES加密测试接口
     */
    @PostMapping("/test_encryption")
    public ApiResponse<Map<String, Object>> testEncryption(@RequestBody Map<String, Object> request) {
        try {
            // 解密请求（如果需要）
            String decryptedData = encryptionService.decryptRequestIfNeeded(request);
            
            // 创建响应数据
            Map<String, Object> result = new HashMap<>();
            result.put("message", "AES加密测试成功");
            result.put("receivedData", decryptedData);
            result.put("isEncrypted", encryptionService.isEncryptedRequest(request));
            result.put("timestamp", System.currentTimeMillis());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
} 